<template>
  <div>
    <div class="subject-con">
      <h2 class="subject">使用{{ msg }}支付</h2>
      <p class="num">
        <span class="rmb-icon">￥</span
        ><span class="amount">{{ Totol }}.00</span>
      </p>
      <!---->
    </div>
    <div class="pawbox">
      <!-- 密码输入框 -->
      <van-password-input
        :value="value"
        :focused="showKeyboard"
        :error-info="errorInfo"
        @focus="showKeyboard = true"
        class="inpaws"
      />
      <!-- 数字键盘 -->
      <van-number-keyboard
        v-model="value"
        :show="showKeyboard"
        @blur="showKeyboard = false"
      />
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";

export default {
  data() {
    return {
      msg: "",
      value: "",
      showKeyboard: true,
      errorInfo: "",
    };
  },
  mounted() {
    this.socketApi.initWebSocket();
  },
  methods: {
    getview(to, from) {
      this.msg = this.$route.params.msg;
    },
    async getPwd() {
      const { data: res } = await this.$http.get("payPwd", {
        params: { pwd: this.value, userID: this.emailLogin[0].userID },
      });

      if (res.status == 200) {
        setTimeout(() => {
          if (this.msg == "微信") {
            this.$toast.success("支付成功");
            setTimeout(() => {
              this.addReceived();
              // this.addallorder();
              this.removeOrder();
              this.sendOrderMsg();
              this.addConsumptionInfo();
              this.$toast.clear();
              this.value = "";
              window.localStorage.removeItem("Totol");
              window.localStorage.removeItem("checkoutList");
              this.$store.commit("delechkoutlist", []);
              window.localStorage.removeItem("recList");
              this.$router.push("/Cat");
            }, 1000);
          } else {
            this.QueryBalance();
          }
        }, 1200);
      } else {
        this.errorInfo = "密码错误！请核对";
        this.value = "";
      }
    },
    async addReceived() {
      var arry2 = [];

      var date = new Date();

      var year = date.getFullYear(); //年 ,从 Date 对象以四位数字返回年份
      var month = date.getMonth() + 1; //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
      var day = date.getDate(); //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)

      var hours = date.getHours(); //小时 ,返回 Date 对象的小时 (0 ~ 23)
      var minutes = date.getMinutes(); //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
      var seconds = date.getSeconds(); //秒 ,返回 Date 对象的秒数 (0 ~ 59)
      var currentFormatDate =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;
      try {
        console.log(this.getProjectNum + Math.floor(Math.random() * 10000));
        this.CheckoutList.map((item, index) => {
          arry2.push(
            Object.assign({}, item, {
              userID: this.emailLogin[0].userID,
              OrderNum: this.getProjectNum + Math.floor(Math.random() * 10000),
              newTime: currentFormatDate,
              orderState: "待发货",
              addressID: this.$store.state.SelectAddress.id,
            })
          );
        });
      } catch (error) {}
      console.log(arry2);
      const { data: res } = await this.$http.post("addAllOrder", arry2);

      //    console.log(res);
    },
    async addallorder() {
      var arry2 = [];

      var date = new Date();

      var year = date.getFullYear(); //年 ,从 Date 对象以四位数字返回年份
      var month = date.getMonth() + 1; //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
      var day = date.getDate(); //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)

      var hours = date.getHours(); //小时 ,返回 Date 对象的小时 (0 ~ 23)
      var minutes = date.getMinutes(); //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
      var seconds = date.getSeconds(); //秒 ,返回 Date 对象的秒数 (0 ~ 59)
      var currentFormatDate =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;
      console.log(this.$store.state.SelectAddress.id);
      this.recList.map((item, index) => {
        arry2.push(
          Object.assign({}, item, {
            newTime: currentFormatDate,
            orderState: "待发货",
            addressID: this.$store.state.SelectAddress.id,
          })
        );
      });

      const { data: res } = await this.$http.post("addAllOrder", arry2);
      console.log(res);
    },
    async removeOrder() {
      const { data: res } = await this.$http.get("deleOrder", {
        params: { num: this.OrderNum },
      });
      if (res.status == 200) {
        window.localStorage.removeItem("time");
        window.localStorage.removeItem("OrderNum");
        window.localStorage.removeItem("myEndTime");
      }
    },
    //增加消费支出
    async addConsumptionInfo() {
      let data = {
        conType: "购物-消费",
        time: new Date(),
        Expenditure: this.Totol,
        Benefit: 0,
        typeIcon:
          "https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/zhichu_gw.png",
        userID: this.emailLogin[0].userID,
      };
      const { data: res } = await this.$http.post("addConsumptionInfo", data);
      console.log(res);
    },
    //扣除相应金额
    async DeductionAmount() {
      const { data: res } = await this.$http.post("ExcludingAmount", {
        price: this.Totol,
        uid: this.emailLogin[0].userID,
      });
      console.log(res);
    },
    //发送订单消息
    async sendOrderMsg() {
      console.log("发送了");
      let data = {
        userID: this.emailLogin[0].userID,
        receive_id: 1,
        Nickname: this.emailLogin[0].Nickname,
        Time: new Date(),
        title: "来自" + this.emailLogin[0].Nickname + "的订单！",
        msgType: 12, //代表订单消息
        textType: "订单",
      };
      this.socketApi.handleSendMsg(data);
    },
    //查询余额
    async QueryBalance() {
      const { data: res } = await this.$http.get("QueryAmount", {
        params: { uid: this.emailLogin[0].userID },
      });
      console.log(res);
      console.log(this.Totol);
      console.log(this.emailLogin[0].userID);

      if (res.Amount.Account_balance > this.Totol) {
        this.$toast.success("支付成功");
        setTimeout(() => {
          this.addReceived();
          // this.addallorder();
          this.removeOrder();
          this.sendOrderMsg();
          this.addConsumptionInfo();
          this.$toast.clear();
          this.value = "";
          window.localStorage.removeItem("Totol");
          window.localStorage.removeItem("CheckoutList");
          window.localStorage.removeItem("recList");
          this.DeductionAmount();
          this.$router.push("/Cat");
        }, 1200);
      } else {
        this.$toast("余额不足！");
      }
    },
  },
  computed: {
    ...mapState(["Totol", "emailLogin", "CheckoutList", "recList", "OrderNum"]),
    ordernum() {
      var orderCode = 0;
      for (
        var i = 0;
        i < 6;
        i++ //6位随机数，用以加在时间戳后面。
      ) {
        orderCode += Math.floor(Math.random() * 10);
      }
      orderCode = new Date().getTime() + orderCode; //时间戳，用来生成订单号。

      return orderCode;
    },
    getProjectNum() {
      const projectTime = new Date(); // 当前中国标准时间
      const Year = projectTime.getFullYear(); // 获取当前年份 支持IE和火狐浏览器.
      const Month = projectTime.getMonth() + 1; // 获取中国区月份
      const Day = projectTime.getDate(); // 获取几号
      var CurrentDate = Year;
      if (Month >= 10) {
        // 判断月份和几号是否大于10或者小于10
        CurrentDate += Month;
      } else {
        CurrentDate += "0" + Month;
      }
      if (Day >= 10) {
        CurrentDate += Day;
      } else {
        CurrentDate += "0" + Day;
      }
      return CurrentDate;
    },
  },
  watch: {
    $route: {
      handler(newVal, oldVal) {
        this.getview(newVal, oldVal);
      },
      deep: true,
      immediate: true,
    },
    value(value) {
      if (value.length === 6) {
        this.$toast.loading({
          forbidClick: true,
          message: "正在核对密码",
          loadingType: "spinner",
        });
        setTimeout(() => {
          this.$toast.clear();
          this.getPwd();
        }, 1500);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.subject-con {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  min-height: 9.16rem;
  line-height: 6rem;
  padding-bottom: 2.05rem;
  /* margin-bottom: 5.2rem; */
  background: white;
  .subject {
    color: #333;
    font-size: 1.2rem;
  }
  .num {
    height: 0.45rem;
    color: #fd0000;
    line-height: 0.45rem;
    font-family: UDC-Bold;
    font-size: 0;
    font-weight: 700;
    margin-top: 0.05rem;
  }
  .rmb-icon {
    font-size: 1rem;
  }
  .amount {
    font-size: 1.6rem;
  }
}
.pawbox {
  background: #fff;
}
</style>